package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.service.FormulaExplainService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.FormulaExplainGetDTO;
import com.xbongbong.pro.formexplain.pojo.vo.FormulaExplainGetVO;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @version 1.0
 * @date 2020-02-07 13:49
 * @since 1.0
 **/
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/formula/explain")
public class FormulaExplainController {


    @Resource
    private FormulaExplainService formulaExplainService;


    /**
     * 获取某个表单的使用公式计算的字段
     * yapi地址：http://yapi.xbongbong.com/project/87/interface/api/14242
     * @param formulaExplainGetDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/ruleList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String ruleList(@RequestBody @Valid FormulaExplainGetDTO formulaExplainGetDTO, BindingResult br) {
        XbbResponse<FormulaExplainGetVO> response;
        if(br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                FormulaExplainGetVO formExplainListVO = formulaExplainService.ruleFormulaList(formulaExplainGetDTO);
                response = new XbbResponse<>(formExplainListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
